<template>
  <div class="legel-management">
    <!-- 查询区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="文件标题">
          <el-input v-model="searchForm.title" placeholder="请输入文件标题" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="文件类型">
          <el-select v-model="searchForm.fileType" placeholder="请选择文件类型" style="width: 180px;">
            <el-option label="法律、法规及行政法规" value="1"></el-option>
            <el-option label="变更管理" value="2"></el-option>
            <el-option label="服务类、环境保护论文" value="3"></el-option>
            <el-option label="服务类、环境保护文档" value="4"></el-option>
            <el-option label="污染水空气宣传资料" value="5"></el-option>
            <el-option label="其他环境保护管理资料" value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-area">
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </div>

    <!-- 表格展示 -->
    <div class="table-area">
      <el-table :data="fileList" style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="title" label="文件标题" ></el-table-column>
        <el-table-column prop="orgName" label="发文单位" width="400"></el-table-column>
        <el-table-column prop="fileTypeName" label="文件类型" width="400"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDownload(scope.row)">下载</el-button>
            <el-button type="text" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 新增/修改弹出框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="文件标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入文件标题"></el-input>
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-select v-model="formData.fileType" placeholder="请选择文件类型">
            <el-option label="法律、法规及行政法规" value="1"></el-option>
            <el-option label="变更管理" value="2"></el-option>
            <el-option label="服务类、环境保护论文" value="3"></el-option>
            <el-option label="服务类、环境保护文档" value="4"></el-option>
            <el-option label="污染水空气宣传资料" value="5"></el-option>
            <el-option label="其他环境保护管理资料" value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发文单位" prop="orgName">
          <el-input v-model="formData.orgName" placeholder="请输入发文单位"></el-input>
        </el-form-item>
        <el-form-item label="文件上传" prop="file">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="handleBeforeUpload"
            :file-list="fileUploadList"
            :auto-upload="true"
            accept=".pdf,.doc,.docx,.xls,.xlsx"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传PDF、Word、Excel文件，单个文件不超过10MB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'LegelManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        title: '',
        fileType: ''
      },
      // 文件列表
      fileList: [],
      // 总数
      total: 0,
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      // 新增/修改弹出框
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      // 表单数据
      formData: {
        id: '',
        title: '',
        fileType: '',
        orgName: '',
        filePath: ''
      },
      // 文件上传列表
      fileUploadList: [],
      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入文件标题', trigger: 'blur' },
          { min: 1, max: 200, message: '文件标题长度在1-200个字符', trigger: 'blur' }
        ],
        fileType: [
          { required: true, message: '请选择文件类型', trigger: 'change' }
        ],
        orgName: [
          { required: true, message: '请输入发文单位', trigger: 'blur' },
          { min: 1, max: 100, message: '发文单位长度在1-100个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 获取数据
    async loadData() {
      try {
        const params = {
          ...this.searchForm,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
        // 实际项目中调用API获取数据
        // const res = await getLegelFiles(params)
        // if (res.code === 200) {
        //   this.fileList = res.rows
        //   this.total = res.total
        // }
        
        // 模拟数据
        this.fileList = [
          {
            id: '1',
            title: '突发生态环境事件应急处置前评估经济损失工作指导规定',
            orgName: '环境保护部',
            fileType: '1',
            fileTypeName: '法律、法规及行政法规',
            filePath: '/upload/file1.pdf'
          },
          {
            id: '2',
            title: '突发生态环境事件应急处置前评估经济损失指南',
            orgName: '环境保护部',
            fileType: '1',
            fileTypeName: '法律、法规及行政法规',
            filePath: '/upload/file2.pdf'
          }
        ]
        this.total = this.fileList.length
      } catch (error) {
        this.$message.error('获取数据失败')
        console.error('获取数据失败:', error)
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadData()
    },
    
    // 重置
    handleReset() {
      this.searchForm = {
        title: '',
        fileType: ''
      }
      this.loadData()
    },
    
    // 新增
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增法律文件'
      this.resetForm()
      this.dialogVisible = true
    },
    
    // 修改
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '修改法律文件'
      this.formData = { ...row }
      // 设置文件上传列表
      if (row.filePath) {
        this.fileUploadList = [{
          name: row.title,
          url: row.filePath
        }]
      }
      this.dialogVisible = true
    },
    
    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除该文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 实际项目中调用API删除文件
          // const res = await deleteLegelFile(row.id)
          // if (res.code === 200) {
          //   this.$message.success('删除成功')
          //   this.loadData()
          // }
          
          // 模拟删除
          this.fileList = this.fileList.filter(item => item.id !== row.id)
          this.total = this.fileList.length
          this.$message.success('删除成功')
        } catch (error) {
          this.$message.error('删除失败')
          console.error('删除失败:', error)
        }
      }).catch(() => {
        // 取消删除
      })
    },
    
    // 下载
    handleDownload(row) {
      // 实际项目中调用下载API
      // this.$download.download(row.filePath, row.title)
      this.$message.success('文件下载中...')
    },
    
    // 关闭弹出框
    handleClose() {
      this.dialogVisible = false
      this.resetForm()
    },
    
    // 重置表单
    resetForm() {
      this.formData = {
        id: '',
        title: '',
        fileType: '',
        orgName: '',
        filePath: ''
      }
      this.fileUploadList = []
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
    },
    
    // 文件上传前校验
    handleBeforeUpload(file) {
      const fileSize = file.size / 1024 / 1024
      if (fileSize > 10) {
        this.$message.error('文件大小不能超过10MB')
        return false
      }
      return true
    },
    
    // 文件上传成功
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.formData.filePath = res.url
        this.$message.success('文件上传成功')
      } else {
        this.$message.error('文件上传失败: ' + (res.msg || '未知错误'))
      }
    },
    
    // 文件上传失败
    handleUploadError(err) {
      this.$message.error('文件上传失败')
      console.error('文件上传失败:', err)
    },
    
    // 提交表单
    async handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            // 验证是否上传文件
            if (!this.formData.filePath) {
              this.$message.error('请上传文件')
              return
            }
            
            // 实际项目中调用API保存数据
            // let res
            // if (this.isEdit) {
            //   res = await updateLegelFile(this.formData)
            // } else {
            //   res = await addLegelFile(this.formData)
            // }
            // if (res.code === 200) {
            //   this.$message.success(this.isEdit ? '修改成功' : '新增成功')
            //   this.dialogVisible = false
            //   this.loadData()
            // }
            
            // 模拟保存
            if (this.isEdit) {
              // 修改现有数据
              const index = this.fileList.findIndex(item => item.id === this.formData.id)
              if (index !== -1) {
                this.fileList[index] = { 
                  ...this.formData,
                  fileTypeName: this.getFileTypeText(this.formData.fileType)
                }
              }
            } else {
              // 新增数据
              const newFile = {
                ...this.formData,
                id: Date.now().toString(),
                fileTypeName: this.getFileTypeText(this.formData.fileType)
              }
              this.fileList.unshift(newFile)
              this.total++
            }
            
            this.$message.success(this.isEdit ? '修改成功' : '新增成功')
            this.dialogVisible = false
          } catch (error) {
            this.$message.error(this.isEdit ? '修改失败' : '新增失败')
            console.error('保存失败:', error)
          }
        }
      })
    },
    
    // 获取文件类型文本
    getFileTypeText(value) {
      const typeMap = {
        '1': '法律、法规及行政法规',
        '2': '变更管理',
        '3': '服务类、环境保护论文',
        '4': '服务类、环境保护文档',
        '5': '污染水空气宣传资料',
        '6': '其他环境保护管理资料'
      }
      return typeMap[value] || ''
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size
      this.loadData()
    },
    
    // 当前页码变化
    handleCurrentChange(current) {
      this.currentPage = current
      this.loadData()
    }
  }
}
</script>

<style scoped>
.legel-management {
  padding: 20px;
}

.search-area {
  background-color: #f5f7fa;
  border-radius: 4px;
}

.action-area {
  margin-bottom: 20px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-upload {
  width: 100%;
}
</style>